package com.intelligent.config;

import com.intelligent.utils.HttpStatus;
import com.intelligent.utils.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一为返回的 Result 添加 success 标记（不修改原有方法）
 */
@RestControllerAdvice
public class SuccessFlagResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 对所有响应进行处理
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response) {
        if (body instanceof Result) {
            Result<?> result = (Result<?>) body;
            // 仅当没有success键时添加，避免重复/覆盖
            if (!result.containsKey("success")) {
                Object code = result.get(Result.CODE_TAG);
                boolean ok = (code instanceof Integer) && ((Integer) code) == HttpStatus.SUCCESS;
                result.put("success", ok);
            }
            return result;
        }
        return body;
    }
}
